﻿@{
    Layout = "~/Views/Shared/_FormWhite.cshtml";
}

@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
@section header{
    <link href="@Url.Content("~/lib/summernote/0.8.15/summernote.min.css")" rel="stylesheet" type="text/css">
    <script src='@Url.Content("~/lib/summernote/0.8.15/summernote.js")' type="text/javascript"></script>
    <script src='@Url.Content("~/lib/summernote/0.8.15/lang/summernote-zh-CN.min.js")' type="text/javascript"></script>

    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/imageupload/1.0/css/imgup.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/imageupload/1.0/js/imgup.min.js"))

    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.js"))


     <!--引入 element-ui 的样式，-->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 必须先引入vue，  后使用element-ui -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <!-- 引入element 的组件库-->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <style type="text/css">
        .el-upload__input {
    display: none !important;
}
        .custom-upload {
  display: inline-block;
}

.custom-upload .el-upload__tip {
  display: none; /* 隐藏提示文本 */
}

.custom-upload .el-upload-list__item-name {
  display: none; /* 隐藏文件名 */
}

.custom-upload .el-upload-list__item-thumbnail {
  display: none; /* 隐藏文件缩略图 */
}

.custom-uploads .el-upload--picture-card {
  width: 148px;
  height: 148px;
}
    </style>
}


<div id="app" class="wrapper animated fadeInRight">
    <el-form ref="form" style="margin-top:20px" :model="form" label-width="80px">
        <el-form-item style="margin-top:20px" label="门店">
            <el-select v-model="form.shopid"
                       style="width:100%"
                       placeholder="请选择门店"
                       v-on:change="handleShopChange">
                <el-option v-for="item in ShopList"
                           :key="item.Id"
                           :label="item.shop_name"
                           :value="item.Id">
                    {{item.shop_name}}
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item style="margin-top:20px" label="品牌">
            <el-select v-model="form.brand_id"
                       style="width:100%"
                       placeholder="请选择品牌">
                <el-option v-for="item in BrandList"
                           :key="item.Id"
                           :label="item.name"
                           :value="item.Id">
                    {{item.name}}
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item style="margin-top:20px" label="产品种类">
            <el-radio-group v-model="form.goods_type" v-on:change="handleRadioGoodsTypeChange">
                <el-radio-button v-for="item in ProductVarietyList" :label="item.Id">{{item.name}}</el-radio-button>
            </el-radio-group>
        </el-form-item>

        <el-form-item style="margin-top:20px" label="属性分类">
            <el-select v-model="form.Type"
                       style="width:100%"
                       placeholder="请选择属性分类"
                       v-on:change="handleRadioTypeChange">
                <el-option v-for="item in form.GoodsTypesList"
                           :key="item.Id"
                           :label="item.type_name"
                           :value="item.Id">
                    {{item.type_name}}
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item v-if="form.goods_type==1" style="margin-top:20px" label="出租分类">
            <el-select v-model="form.category_id"
                       style="width:100%"
                       placeholder="请选择出租分类"
                       v-on:change="handleRentCategoryChange">
                <el-option v-for="item in form.RentCategoryList"
                           :key="item.Id"
                           :label="item.category_name"
                           :value="item.Id">
                    {{item.category_name}}
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item style="margin-top:20px" label="属性参数">
            <el-card class="box-card" shadow="never" style="background:#f8f9fc;">
                <div v-for="(group, index) in form.BaseGoodsAttrList" :key="group.Id" style="margin-top:5px">
                    {{ group.attribute_name }}:
                    <el-checkbox-group v-if="group.allowfile" v-model="dynamicCheckboxGroups[group.attribute_name]" size="mini">
                        <el-checkbox v-for="(item, itemIndex) in group.input_list.split('|')"
                                     :key="itemIndex"
                                     :label="item.trim()"
                                     v-on:change="handleCheckboxClickSet(group.attribute_name, item,group.Id)"
                                     border>
                            {{ item.trim() }}
                        </el-checkbox>
                    </el-checkbox-group>

                    <el-checkbox-group v-else v-model="dynamicCheckboxGroups[group.attribute_name]" size="mini">
                        <el-checkbox v-for="(item, itemIndex) in group.input_list.split('|')"
                                     :key="itemIndex"
                                     :label="item.trim()"
                                     v-on:change="handleCheckboxClick2(group.attribute_name, item,group.Id)"
                                     border>
                            {{ item.trim() }}
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
            </el-card>
        </el-form-item>

        <el-form-item>
            <el-card v-if="skupicAttr.length>0" class="box-card" shadow="never" style="background:#f8f9fc;">
                <el-table :data="skupicAttr"
                          border
                          size="mini"
                          style="width: 100%">
                    <el-table-column prop="name"
                                     width="200"
                                     align="center"
                                     label="标题">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.name"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="value"
                                     width="200"
                                     align="center"
                                     :label="lablePic">
                        <template slot-scope="scope">
                            <span>{{scope.row.value}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="image"
                                     align="center"
                                     width="168"
                                     label="封面">
                        <template slot-scope="scope">
                            <el-upload :action="uploadUrl"
                                       list-type="picture-card"
                                       :hide-input="true"
                                       :multiple="false"
                                       :on-success="(response, file, fileList) => handlePicSuccess(response, file, fileList,scope.$index)"
                                       class="custom-upload"
                                       :show-file-list="false"
                                       :on-remove="handleRemove">
                                <img v-if="scope.row.pic" style="width:100%" :src="scope.row.pic" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-form-item>

        <el-form-item>
            <el-card class="box-card" shadow="never" style="background:#f8f9fc;">
                <el-table :data="tableDataAttr"
                          border
                          size="mini"
                          style="width: 100%">
                    <el-table-column prop="sku_code"
                                     width="200"
                                     align="center"
                                     label="SKU货号">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.sku_code"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sku_name"
                                     width="200"
                                     align="center"
                                     label="SKU名称">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.sku_name"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column v-for="(column, index) in columns"
                                     :key="index"
                                     :prop="column"
                                     align="center"
                                     :label="column"></el-table-column>
                    @*<el-table-column prop="pic"
                                     align="center"
                                     width="168"
                                     label="商品图片">
                        <template slot-scope="scope">
                            <el-upload :action="uploadUrl"
                                       list-type="picture-card"
                                       :hide-input="true"
                                       :multiple="false"
                                       :on-success="(response, file, fileList) => handlePictureSuccess(response, file, fileList,scope.$index)"
                                       class="custom-upload"
                                       :show-file-list="false"
                                       :on-remove="handleRemove">
                                <img v-if="scope.row.pic" style="width:100%" :src="scope.row.pic" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </template>
                    </el-table-column>*@
                    <el-table-column prop="price"
                                     align="center"
                                     label="价格">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.price"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="stock"
                                     align="center"
                                     label="商品库存">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.stock"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="isDefault"
                                     align="center"
                                     label="默认商品">
                        <template slot="header" slot-scope="scope">
                            默认商品
                            <el-button type="primary" size="mini" v-on:click="handleShuaXin" icon="el-icon-circle-plus-outline">刷新</el-button>
                        </template>
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.isDefault"
                                       active-color="#13ce66"
                                       inactive-color="#ff4949"
                                       active-value="1"
                                       inactive-value="0"
                                       v-on:change="handleSwitchChange(scope.row,scope.$index)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    @*<el-table-column prop="CZ">
                        <template slot="header" slot-scope="scope">
                            <el-button type="primary" size="mini" v-on:click="handleShuaXin" icon="el-icon-circle-plus-outline">刷新</el-button>
                        </template>
                        <template slot-scope="scope">
                            <el-button size="mini"
                                       type="danger"
                                       v-on:click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>*@
                </el-table>
            </el-card>
        </el-form-item>

        <el-form-item v-if="form.goods_type==1" style="margin-top:20px" label="会员折扣">
            <el-card class="box-card" shadow="never">
                <el-row :gutter="5">
                    <el-col :lg="8" v-for="item in form.MemberGrade">
                        <el-input placeholder="请输入会员折扣" v-model="item.memberDiscount">
                            <template slot="prepend">
                                {{item.memberName}}
                                <font style="color:red !important"> *</font>
                            </template>
                        </el-input>
                    </el-col>
                </el-row>
                <ul>
                    <li class="list-item" style="color:#606266 !important">会员折扣为0时，使用默认价格。大于0时，商品实际价格=货品销售价*会员价折扣</li>
                </ul>
            </el-card>
        </el-form-item>

        <el-form-item label="商品名称">
            <el-input v-model="form.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品编号">
            <el-row :gutter="5">
                <el-col :lg="20"><div class="grid-content bg-purple"><el-input v-model="form.goods_core" disabled></el-input></div></el-col>
                <el-col :lg="3"><div class="grid-content bg-purple-light"><el-button type="primary" v-on:click="crategoodscore()">生成商品编号</el-button></div></el-col>
            </el-row>
        </el-form-item>
        <el-form-item label="商品价格">
            <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item v-if="form.goods_type!=1" label="会员折扣">
            <el-input v-model="form.discount"></el-input>
        </el-form-item>
        <el-form-item label="单位">
            <el-input v-if="form.goods_type==1" disabled v-model="form.unit"></el-input>
            <el-input v-else v-model="form.unit"></el-input>
        </el-form-item>
        <el-form-item label="是否推荐">
            <el-switch v-model="form.is_master"></el-switch>
        </el-form-item>
        <el-form-item label="是否开启">
            <el-switch v-model="form.is_master"></el-switch>
        </el-form-item>
        <el-form-item label="商品封面">
            <el-upload :action="uploadUrl"
                       list-type="picture-card"
                       :hide-input="true"
                       :on-success="handleGoodsImageSuccess"
                       class="custom-upload"
                       :multiple="false"
                       :show-file-list="false"
                       :on-remove="handleRemove">
                <img v-if="form.goods_image" style="width:100%" :src="form.goods_image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="商品图集">
            <el-upload :action="uploadUrl"
                       list-type="picture-card"
                       :hide-input="true"
                       :multiple="true"
                       :on-success="handleGoodsImagesSuccess"
                       class="custom-uploads"
                       :file-list="form.goods_images"
                       :on-remove="handleGoodsImagesRemove">
                <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="商品简介">
            <div id="goods_brief" class="summernote"></div>
        </el-form-item>
        <el-form-item label="商品详情">
            <div id="goods_intro" class="summernote"></div>
        </el-form-item>
    </el-form>



</div>

<script type="text/javascript">
    var id = ys.request("id");
    var shopid = ys.request("shopid");



     // 创建 Vue 实例
   var vm=new Vue({
        el: '#app',  // 挂载到 id 为 app 的元素
        data: {
            radio2: '自行车',
            tableData: [],
            formLabelWidth: '120px',
            dialogFormVisible: false,
            dialogVisible: false,
            dialogImageUrl: '',
            columns: [],
            tableDataAttr: [],
            skupicAttr: [],
            lablePic:'',
            BrandList:[],
            dynamicCheckboxGroups: {},
            binddynamicCheckboxGroups: {},
            form: {
                Id:0,
                shopid: shopid == "null" ? '' : shopid,
                brand_id:'',
                shop_name:'',
                goods_core:'',
                goods_name:'',
                Type:"1",
                goods_type:"2",
                is_master:"0",
                goods_image:'',
                unit:'',
                goods_images:[],
                checkboxGroup2:[],
                GoodsTypesList:[],
                BaseGoodsAttrList:[],
                GoodsBrandModel:[],
                inputBrandModel:'',
                attrData: [],
                RentCategoryList: [],
                category_name: '',
                category_id: '',
                price:'0',
                //RentModelList: [],
                //goods_model_id: '',
                //goods_model: '',
                car_rental_price: '0',
                discount: '0',
                MemberGrade: [
                ],//会员比例
            },
            ProductVarietyList: [],
            ShopList:[],
		    uploadUrl:'@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.Qixing.ParseToInt()',
		    curRowIndex: null,
            goodsattrVisible: false,
            //formattr: {
            //    Id:0,
            //    color:'',
            //    image:'',
            //    num: '',
            //    price: 0,
            //    isDefault:'0'
            //},
            activeRowIndex: null, // 用于存储当前开启的行的索引
            search: {
                param: {},
                pagination: {
                    currentPage: 1,
                    pagesize: 10,
                    Sort: 'Id',
                    SortType:' desc ',
                    total: 0,
                }
            },
            stripe: true,//是否为斑马纹 table
        },
       methods: {
           getbrandlist()
            {
               var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/BrandInfo/GetListJson")';
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url:queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.BrandList= obj.Data.map(item => ({
                                name: item.brand_name,
                                Id: item.Id,
                            }));
                        }
                    }
                });
            },
           handleShuaXin() {
               const { tableData, columns } = this.processData();


               const result = tableData.map(item => {
                   return Object.keys(item).map(key => ({
                       Key: key,
                       Value: item[key]
                   }));
               });
               // 转换为目标格式
               const DataAttrJSON = result.map(item => {
                   const sku = {
                       sku_code: "", // 这里可以根据需要生成 SKU
                       sku_name: "", // 这里可以根据需要设置 SKU 名称
                       stock: 100,   // 这里可以根据需要设置库存
                       price: 100,   // 这里可以根据需要设置价格
                       pic: "",     // 这里可以根据需要设置图片
                       isDefault: "0", // 这里可以根据需要设置默认值
                       sp_data: JSON.stringify(item)     // 保留原始的 JSON 数据
                   };
                   // 将 JSON 中的 key-value 插入到 sku 对象中
                   item.forEach(attr => {
                       sku[attr.Key] = attr.Value;
                   });
                   return sku;
               });
               // 将第一个 sku 中的 isDefault 设置为 "1"
               if (DataAttrJSON.length > 0) {
                   DataAttrJSON[0].isDefault = "1";
               }
               this.tableDataAttr = DataAttrJSON;

               console.log("result:" + JSON.stringify(DataAttrJSON));
               console.log("tableData:" + JSON.stringify(tableData));

               this.columns = columns;
           },
           // 处理数据的方法，包含过滤和生成全排列组合的逻辑
           processData() {
               const originalData = this.dynamicCheckboxGroups;
               // 过滤掉值为空数组的键值对
               const filteredData = {};
               for (const [key, value] of Object.entries(originalData)) {
                   if (value.length > 0) {
                       filteredData[key] = value;
                   }
               }
               // 生成全排列组合的数据
               const tableData = this.generateCombinations(filteredData);
               console.log(JSON.stringify(tableData));
               const columns = Object.keys(filteredData);


               return { tableData, columns };
           },
           // 生成全排列组合的数据
           generateCombinations(data) {
               const keys = Object.keys(data);
               const values = Object.values(data);
               const result = [];

               function combine(index, current) {
                   if (index === keys.length) {
                       result.push({ ...current });
                       return;
                   }
                   const currentKey = keys[index];
                   for (const item of values[index]) {
                       current[currentKey] = item;
                       combine(index + 1, current);
                   }
               }

               combine(0, {});
               return result;
           },
           //handleRentModelChange(e) {
           //    const selectedRentModel = this.form.RentModelList.find(item => item.Id === e);
           //    if (selectedRentModel) {
           //        this.form.model_name = selectedRentModel.model_name;
           //        this.form.car_rental_price = selectedRentModel.rule;
           //        this.form.unit = selectedRentModel.unit;
           //    } else {
           //        this.form.model_name = '';
           //        this.form.car_rental_price = "0";
           //        this.form.unit = "";
           //    }
           // },
           validateMemberDiscount(discount) {
               const regex = /^0\.\d{1,2}$|^1\.00?$/;
               return discount >= 0 && discount <= 1 && regex.test(discount.toString());
           },
            getMember()
            {
               var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/MemberLevel/GetListJson")';
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url:queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.form.MemberGrade= obj.Data.map(item => ({
                                memberName: item.name,  // 将 "name" 改为 "memberName"
                                memberDiscount: 0,         // 新增 "memberDiscount" 字段，值为 0
                                memberId: item.Id,            // 新增 "memberId" 字段，值为 0
                                goodsId: 0              // 新增 "goodsId" 字段，值为 0
                            }));
                        }
                    }
                });
            },
           handleSwitchChange(row, index) {
               //row.isDefault = Number(row.isDefault);
               // 如果切换后当前行是开启状态
               if (row.isDefault ==='1') {
                   // 如果不是第一次点击，关闭之前开启的行
                   if (this.activeRowIndex !== null && this.activeRowIndex !== index) {
                       this.tableDataAttr[this.activeRowIndex].isDefault = '0';
                   }
                   // 更新当前开启的行索引
                   this.activeRowIndex = index;
               } else {
                   // 如果切换后当前行是关闭状态
                   // 重置 activeRowIndex
                   this.activeRowIndex = null;
               }
            },
            handleRentCategoryChange(e) {
                const selectedRentCategory= this.form.RentCategoryList.find(item => item.Id === e);
                if (selectedRentCategory) {
                    this.form.category_name = selectedRentCategory.category_name;
                    this.form.car_rental_price = selectedRentCategory.rule;
                    this.form.unit = selectedRentCategory.unit;
                } else {
                    this.form.category_name = '';
                    this.form.car_rental_price = "0";
                    this.form.unit = "";
                }
            },
            getRentCategory()
            {
               var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/GoodsCategory/GetListJson")';
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url:queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.form.RentCategoryList = obj.Data;
                        }
                    }
                });
            },
            @*getRentModelList()
            {
               var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/Models/GetListJson")';
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url:queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.form.RentModelList = obj.Data;
                        }
                    }
                });
            },*@
            getGoodsinfo() {
             var that = this;
             ys.ajax({
                url: '@Url.Content("~/QixingManage/Goods/GetNewFormJson")' + '?id=' + id,
                type: 'get',
                async: false, // 设置为同步请求
                success: function (obj) {
                    if (obj.Tag == 1) {
                        that.form.Id = obj.Data.Id;

                        that.GetProductVariety();
                        that.GetGoodsTypes(obj.Data.goods_type, 1);


                        that.form.shop_name = obj.Data.shop_name;
                        that.form.shopid = obj.Data.shop_id;
                        that.form.brand_id = obj.Data.brand_id;
                        that.form.Type = obj.Data.Type;
                        that.form.goods_name = obj.Data.goods_name;
                        that.form.goods_core = obj.Data.goods_core;
                        that.form.goods_type = obj.Data.goods_type;
                        that.form.is_master = obj.Data.is_master;
                        that.form.car_rental_price = obj.Data.car_rental_price;
                        that.form.price = obj.Data.price;
                        that.form.goods_image = obj.Data.goods_image;
                        that.form.goods_images = JSON.parse(obj.Data.goods_images_ext);
                        that.form.unit = obj.Data.unit;
                        that.form.discount = obj.Data.discount;

                        that.GetGoodsBrandModel(1);
                        that.form.inputBrandModel = obj.Data.input_models;

                        that.binddynamicCheckboxGroups = JSON.parse(obj.Data.BaseGoodsAttrList);

                        that.form.MemberGrade = obj.Data.MemberGrade;

                        console.log(JSON.stringify(that.form.MemberGrade))
                        if (that.form.MemberGrade.length == 0) {
                            that.getMember();
                        }

                        console.log(obj.Data.BaseGoodsAttrList);
                        that.initializeSummernote();


                        that.GetBaseGoodsAttr();

                        that.form.attrData = obj.Data.GetList;

                        // 用于存储所有 Key 的集合
                        const keySet = new Set();

                        const processedSkus = obj.Data.goodsSkus.map(sku => {
                            // 解析 sp_data
                            const spData = JSON.parse(sku.sp_data);

                            // 将 sp_data 中的 Key 和 Value 插入到 sku 对象中
                            spData.forEach(item => {
                                sku[item.Key] = item.Value;
                                // 将 Key 添加到集合中
                                keySet.add(item.Key);
                            });

                            return sku;
                        });

                        that.tableDataAttr = processedSkus;

                        that.columns = Array.from(keySet);

                        console.log("goodsSkus:" + JSON.stringify(processedSkus))

                        // 使用 map 方法遍历数组并修改 isDefalut 属性
                        that.form.attrData = that.form.attrData.map(item => {
                            return {
                                ...item,
                                isDefault: String(item.isDefault) // 将 isDefalut 转为字符串
                            };
                        });

                         if (obj.Data.colorsEntities.length > 0)
                         {
                             that.lablePic = obj.Data.colorsEntities[0].key;
                         }

                        that.skupicAttr=obj.Data.colorsEntities

                        console.log(JSON.stringify(that.form.attrData))
                        $("#goods_brief").summernote('code', obj.Data.goods_brief);
                        $("#goods_intro").summernote('code', obj.Data.goods_intro);
                    }
                }
            });
            },
            crategoodscore() {
                this.form.goods_core ="CYQX"+Date.now();
            },
            initializeSummernote(){
              var that = this;
            $('#goods_brief').summernote({
                height: '220px',
                lang: 'zh-CN',
                dialogsInBody: true,
                callbacks: {
                    onImageUpload: function (files, editor, welEditable) {
                        that.uploadNewsImage(files[0], editor, welEditable,$('#goods_brief'));
                    }
                }
            });

            $('#goods_intro').summernote({
                height: '220px',
                lang: 'zh-CN',
                dialogsInBody: true,
                callbacks: {
                    onImageUpload: function (files, editor, welEditable) {
                        that.uploadNewsImage(files[0], editor, welEditable,$('#goods_intro'));
                    }
                }
            });
            },
            uploadNewsImage(file, editor, welEditable,$obj){
                var formdata = new FormData();
                formdata.append("fileList", file);
                ys.ajaxUploadFile({
                    url: '@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.Qixing.ParseToInt()',
                    data: formdata,
                    success: function (obj) {
                        if (obj.Tag == 1)
                        {
                            $obj.summernote('insertImage', '@GlobalContext.SystemConfig.ApiSite' + obj.Data, '/');
                        }
                        else {
                            ys.msgError(obj.Message);
                        }
                    }
                })
            },
            handleShopChange(shopId) {
              debugger;
              // 根据 shopId 查找对应的门店信息
              const selectedShop = this.ShopList.find(item => item.Id === shopId);
              if (selectedShop) {
                this.form.shop_name = selectedShop.shop_name;
                  console.log('选中的门店名称:', this.form.shop_name);
                this.GetProductVariety();
              } else {
                this.form.shop_name = ''; // 如果没有找到，清空 shop_name
              }
            },
            getShopList() {
                var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/Shop/GetListJson")' + '?id=' +that.form.shopid;
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url: queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.ShopList = obj.Data;
                        }
                    }
                });
            },
            GetProductVariety() {
                var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/ProductVariety/GetTenantListJson")' + '?shopid=' + that.form.shopid;
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url: queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.ProductVarietyList = obj.Data;
                            if (that.form.Id==0)
                            {
                                that.GetGoodsTypes(obj.Data[0].Id,0);
                            }
                        }
                    }
                });
            },
            handleRadioTypeChange(e) {
                this.form.Type = e;

                const result = this.form.GoodsTypesList.find(item => item.Id ===e);

                if (result.IsBrandModel == "1") {
                    this.GetGoodsBrandModel(e);
                    this.form.inputBrandModel = "";
                    this.dynamicCheckboxGroups = {};
                }
                else
                {
                    this.form.inputBrandModel = "";
                    this.form.GoodsBrandModel = [];
                    this.dynamicCheckboxGroups = {};
                }
                this.GetBaseGoodsAttr();
            },
            handleRadioGoodsTypeChange(e)
            {
                this.GetGoodsTypes(e,0);
            },
            GetGoodsBrandModel(tid) {
                var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/GoodsTypes/GetGoodsBrandModel")' + '?id=' + tid + '&shopid=' + that.form.shopid;
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url:queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            if (obj.Data.length > 0){
                                 that.form.GoodsBrandModel = obj.Data;
                            }
                            that.form.inputBrandModel = "";
                        }
                    }
                });
            },
             initializeCheckboxGroups() {
              this.form.BaseGoodsAttrList.forEach(group => {
                 this.$set(this.dynamicCheckboxGroups,group.attribute_name, []);
              });
              const data = this.binddynamicCheckboxGroups;
              for (const key in data) {
                if (this.dynamicCheckboxGroups.hasOwnProperty(key)) {
                  data[key].forEach(value => {
                    if (!this.dynamicCheckboxGroups[key].includes(value)) {
                      this.dynamicCheckboxGroups[key].push(value);
                    }
                  });
                }
              }
            },
            handleCheckboxClick(groupId, value) {
              const currentGroup = this.dynamicCheckboxGroups[groupId];
              console.log(JSON.stringify(currentGroup));
              const index = currentGroup.indexOf(value);
              if (index > -1 && currentGroup.length>1) {
                currentGroup.splice(0,1);
              }
              this.form.goods_name =this.combineAttributes();
              console.log(`Checkbox changed for group ${groupId} with value ${value}. Current state:`,JSON.stringify(this.dynamicCheckboxGroups));
           },
           handleCheckboxClick2(groupId, value,id) {
               const currentGroup = this.dynamicCheckboxGroups[groupId];
               console.log(JSON.stringify(currentGroup));
               const index = currentGroup.indexOf(value);
               //if (index > -1 && currentGroup.length > 1) {
               //    currentGroup.splice(0, 1);
               //}
               this.form.goods_name = this.combineAttributes();
               console.log(`Checkbox changed for group ${groupId} with value ${value}.Id ${id}, Current state:`, JSON.stringify(this.dynamicCheckboxGroups));
           },
           handleCheckboxClickSet(groupId, value, id) {
               const currentGroup = this.dynamicCheckboxGroups[groupId];
               console.log(JSON.stringify(currentGroup));
               const index = currentGroup.indexOf(value);
               this.form.goods_name = this.combineAttributes();
               const skupic = {
                   key: groupId,
                   value: value,
                   name:'',
                   pic:'',     // 这里可以根据需要设置图片
               };
               // 检查是否已经存在相同的 value
               const picindex = this.skupicAttr.findIndex(item => item.value === value);

               if (picindex !== -1) {
                   // 如果存在，移除该对象
                   this.skupicAttr.splice(picindex, 1);
               } else {
                   // 如果不存在，添加新对象
                   this.skupicAttr.push(skupic);
               }
               this.lablePic = groupId;
               console.log(`skuimageAttr:`, JSON.stringify(this.skupicAttr));
               //设置颜色方面上传图片
           },
            handleCheckboxClick1(groupId, value, value1) {
                this.form.inputBrandModel = value1
                const currentGroup = this.dynamicCheckboxGroups[groupId];
                console.log(JSON.stringify(currentGroup));
                const index = currentGroup.indexOf(value);
                if (index > -1 && currentGroup.length > 1) {
                    currentGroup.splice(0, 1);
                }
                if (this.form.Id == 0) {
                    this.form.goods_name = this.combineAttributes();
                }
                console.log(`Checkbox changed for group ${groupId} with value ${value}. Current state:`,JSON.stringify(this.dynamicCheckboxGroups));
            },
            GetGoodsTypes(pvid,index) {
                var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/GoodsTypes/GetListJson")' + '?pvid=' + pvid;
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url: queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.form.GoodsTypesList = obj.Data;
                            if (that.form.Id == 0 || index==0) {
                                    that.form.Type = obj.Data[0].Id;
                                    if (obj.Data[0].IsBrandModel=="1")
                                    {
                                        that.GetGoodsBrandModel(obj.Data[0].Id);
                                    }
                                    else
                                    {
                                        that.form.inputBrandModel = "";
                                        that.form.GoodsBrandModel = [];
                                        that.dynamicCheckboxGroups = {};
                                    }
                                    that.GetBaseGoodsAttr();
                            }
                        }
                    }
                });
            },
            GetBaseGoodsAttr() {
                var that = this;
                var queryUrl = '@Url.Content("~/QixingManage/GoodsTypes/GetBaseGoodsAttr")' + '?id=' +that.form.Type;
                $.ajax({
                    type: 'Get',
                    dataType: 'json',
                    url: queryUrl,
                    async: false, // 设置为同步请求
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.form.BaseGoodsAttrList = obj.Data;
                             console.log(JSON.stringify(obj.Data));
                             that.initializeCheckboxGroups();
                        }
                    }
                });
            },
            //取消属性添加
            goodsAttrCancel() {
                this.goodsattrVisible = false;
                this.formattr.color = '';
                this.formattr.image = '';
                this.formattr.num = '';
                this.formattr.price = '0';
                this.formattr.isDefault = '0';
            },
            //属性添加
           goodsAttrSubmit() {
                if (this.form.attrData.length == 0) {
                   this.formattr.isDefault = '1';
                }
                this.form.attrData.push({ ...this.formattr }); // 使用对象展开运算符创建一个新对象
                this.goodsattrVisible = false;
                this.formattr.color = '';
                this.formattr.image = '';
                this.formattr.num = '';
                this.formattr.price = '0';
                this.formattr.isDefault = '0';
            },
            handleDelete(index, row) {
                this.tableDataAttr.splice(index, 1);
            },
           handlePictureSuccess(response, file, fileList, index) {
                console.log(response);
                if (response.Tag==1)
                {
                    this.tableDataAttr[index].pic='@GlobalContext.SystemConfig.ApiSite'+response.Data;
                }
           },
            handlePicSuccess(response, file, fileList, index) {
                console.log(response);
                if (response.Tag==1)
                {
                    this.skupicAttr[index].pic='@GlobalContext.SystemConfig.ApiSite'+response.Data;
                }
            },
            handleGoodsImageSuccess(response, file, fileList) {
                if (response.Tag==1)
                {
                    this.form.goods_image='@GlobalContext.SystemConfig.ApiSite'+response.Data;
                }
            },
            handleGoodsImagesSuccess(response, file, fileList) {
                if (response.Tag==1)
                {
                    let imge='@GlobalContext.SystemConfig.ApiSite' + response.Data;
                    let filejson = {
                        url: imge,
                        name: file.name,
                        uid: response.uid,  // 假设 uid 在 response 中
                        status: response.status  // 假设 status 在 response 中
                    };
                    this.form.goods_images.push(filejson); // 使用对象展开运算符创建一个新对象
                }
            },
            convertUrlsToString(imagesArray) {
              // 确保 imagesArray 是一个数组
              if (!Array.isArray(imagesArray)) {
                console.error('imagesArray 不是一个数组');
                return '';
              }
              // 使用 map 方法提取 url，并使用 join 方法将 URL 拼接成逗号分隔的字符串
              return imagesArray.map(image => image.url).join(';');
            },
            handleGoodsImagesRemove(file, fileList) {
                // 处理图片移除的逻辑
                this.form.goods_images = fileList.filter(item => item.uid !== file.uid);
            },
		    handleError(err, file, fileList){

		    },
           handleAddattr() {
               if (this.form.goods_type == 1 && this.form.attrData.length>0)
                {
                    ys.msgError("租车类型只有一个SKU参数!");
                    return;
                }
                this.goodsattrVisible = true;
            },
            handleRemove(file, fileList) {

            },
            handleClick: function (row) {
                this.dialogFormVisible = true;
            },
            combineAttributes() {
              // 提取所有数组值，并将它们合并成一个数组
              const valuesArray = Object.values(this.dynamicCheckboxGroups).flat();
              // 将数组值组合成字符串，用逗号分隔
              const combinedString = valuesArray.join('');

              return combinedString;
            }
        },
        created() {
            console.log('Vue instance created');
       },
       computed: {
           defaultItemExists() {
               return this.form.attrData.some(item => item.isDefault === "1");
           }
       },
        mounted() {
            this.getShopList();
            this.getbrandlist();
            this.getRentCategory();
            //this.getRentModelList();弃用
            if (id > 0) {
                this.getGoodsinfo();
            }
            else
            {
                this.GetGoodsBrandModel(1);
                this.getMember();
            }
            if (id==0)
            {
                this.GetProductVariety();
                this.GetBaseGoodsAttr();
                this.initializeSummernote();
            }
            //this.GetGoodsTypes();
        }
    });
    function saveForm(index) {
           var postData ={ Id: id };

            postData.goods_image =vm.form.goods_image;

            postData.shop_id =vm.form.shopid;

            postData.goods_images =vm.convertUrlsToString(vm.form.goods_images);

            postData.goods_images_ext = JSON.stringify(vm.form.goods_images);

            postData.Type = vm.form.Type;


            postData.is_master = vm.form.is_master;
            postData.goods_name = vm.form.goods_name;
            postData.unit = vm.form.unit;
            postData.goods_core=vm.form.goods_core;
            postData.goods_type = vm.form.goods_type;
            postData.price = vm.form.price;
            postData.discount = vm.form.discount;
            postData.car_rental_price = vm.form.car_rental_price;
            postData.goods_brief = $("#goods_brief").summernote('code');
            postData.goods_intro = $("#goods_intro").summernote('code');
            postData.BaseGoodsAttrList = JSON.stringify(vm.dynamicCheckboxGroups);
            postData.colorsEntities = vm.skupicAttr;

            postData.input_models=vm.form.inputBrandModel;
            /*postData.GetList = vm.form.attrData;*/
            postData.goodsSkus = vm.tableDataAttr;

            //if (!vm.defaultItemExists) {
            //    return ys.msgError("必须选择一个默认商品!");
            //}
            postData.MemberGrade = vm.form.MemberGrade;

            for (let item of postData.MemberGrade) {
                if (item.memberDiscount != 0) {
                    if (!vm.validateMemberDiscount(item.memberDiscount)) {
                        return ys.msgError(`${item.memberDiscount} 不合规，必须在 0 到 1 之间且小数部分不能超过两位`);
                    }
                }
           }
            postData.brand_id = vm.form.brand_id;
            postData.category_id = vm.form.category_id;
            postData.category_name = vm.form.category_name;
            //postData.car_rental_price = vm.form.car_rental_price;
            console.log(JSON.stringify(postData));
            if (ys.isNullOrEmpty(postData.shop_id)) {
                return ys.msgError("请选择店铺!");
            }
            if (ys.isNullOrEmpty(postData.shop_name)) {
                const selectedShop = vm.ShopList.find(item => item.Id ===postData.shop_id);
                if (selectedShop) {
                    vm.form.shop_name = selectedShop.shop_name;
                    postData.shop_name = vm.form.shop_name;
                } else {
                    return ys.msgError("请选择店铺!");
                }
            }

            if (postData.goods_type < 4) {
                if (postData.goods_type == 1)
                {
                    if (ys.isNullOrEmpty(postData.category_id)) {
                        return ys.msgError("请选择出租分类!");
                    }
                }
                //判断型号是否存在值
                //if (vm.dynamicCheckboxGroups.品牌) {
                //    if (vm.dynamicCheckboxGroups.品牌.length <= 0) {
                //        return ys.msgError("请选择商品品牌!");
                //    }
                //}
                //else
                //{
                //    return ys.msgError("未找到商品品牌，请联系管理员!");
                //}

                //if (vm.dynamicCheckboxGroups.型号) {
                //    if (vm.dynamicCheckboxGroups.型号.length <= 0) {
                //        return ys.msgError("请选择商品型号!");
                //    }
                //}
                //else
                //{
                //    return ys.msgError("未找到商品型号，请联系管理员!");
                //}
            }

            if (ys.isNullOrEmpty(postData.goods_core)) {
                return ys.msgError("请生成商品编号!");
            }
            if (ys.isNullOrEmpty(postData.goods_name)) {
                return ys.msgError("请填写商品名称!");
            }
            if (ys.isNullOrEmpty(postData.price)) {
                return ys.msgError("请填写商品价格!");
            }
            if (ys.isNullOrEmpty(postData.goods_type)) {
                return ys.msgError("请选择商品种类!");
            }
            if (ys.isNullOrEmpty(postData.goods_image)) {
                return ys.msgError("请上传商品封面!");
            }
            if (ys.isNullOrEmpty(vm.form.goods_images)) {
                return ys.msgError("请上传商品图集!");
            }
            ys.ajax({
                url: '@Url.Content("~/QixingManage/Goods/NewSaveFormJson")',
                type: 'post',
                data: postData,
                success: function (obj) {
                    if (obj.Tag == 1) {
                        ys.msgSuccess(obj.Message);
                        if (id > 0) {
                            parent.searchPageGrid();
                        }
                        else
                        {
                            parent.searchGrid();
                        }

                        parent.layer.close(index);
                    }
                    else {
                        ys.msgError(obj.Message);
                    }
                }
            });
    }
</script>

